{% extends 'base.html' %}

{% block page-content %}
    <div class="container">
        <div class="row" style="margin-top: 20px">
            <div class="col-xs-12">
                <div class="panel panel-green">
                    <div class="panel-heading">上传数据</div>
                    <div class="panel-body pan">
                        <form class="form-horizontal" role="form" enctype="multipart/form-data" id="uploadData">
                            <div class="form-body pal">
                                <div class="form-group">
                                    <label for="inputUsername" class="col-md-3 control-label">数据类型
                                    </label>
                                    <div class="col-md-9">
                                        <div class="input-icon">
                                            <select class="form-control" v-model="RecType" name="RecType">
                                                <option v-for="(typeitem,index) in dataTypeList" :value="typeitem.Name">
                                                    [[typeitem.Name]]
                                                </option>

                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="inputUsername" class="col-md-3 control-label">标题
                                    </label>
                                    <div class="col-md-9">
                                        <div class="input-icon">
                                            <input class="form-control" type="text" placeholder=""
                                                   name="Title"
                                                   v-model="Title"/>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="inputUsername" class="col-md-3 control-label">简介
                                    </label>
                                    <div class="col-md-9">
                                        <div class="input-icon">
                                            <textarea class="form-control" rows="3" cols="80" name="Abstract"
                                                      v-model="Abstract"></textarea>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="inputUsername" class="col-md-3 control-label">详细描述
                                    </label>
                                    <div class="col-md-9">
                                        <div class="input-icon">
                                            <textarea class="form-control" rows="3" cols="80" name="Content"
                                                      v-model="Content"></textarea>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="inputUsername" class="col-md-3 control-label">介绍图片
                                    </label>
                                    <div class="col-md-9">
                                        <div class="upload">
                                            <div class="upload_warp">
                                                <div class="upload_warp_left" @click="fileClick">
                                                    <img src="/static/images/upload.png">
                                                </div>
                                                {#                                                <div class="upload_warp_right" @drop="drop($event)"#}
                                                {#                                                     @dragenter="dragenter($event)" @dragover="dragover($event)">#}
                                                {#                                                    或者将文件拖到此处#}
                                                {#                                                </div>#}
                                            </div>
                                            <div class="upload_warp_text">
                                                选中[[imgList.length]]张文件，共[[bytesToSize(this.size)]]
                                            </div>
                                            <input @change="fileChange($event)" type="file" id="upload_file" multiple
                                                   style="display: none"/>
                                            <div class="upload_warp_img" v-show="imgList.length!=0">
                                                <div class="upload_warp_img_div" v-for="(item,index) of imgList">
                                                    <div class="upload_warp_img_div_top">
                                                        <div class="upload_warp_img_div_text">
                                                            [[item.file.name]]
                                                        </div>
                                                        <img src="/static/images/del.png"
                                                             class="upload_warp_img_div_del"
                                                             @click="fileDel(index)">
                                                    </div>
                                                    <img :src="item.file.src">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="inputUsername" class="col-md-3 control-label">数据文件
                                    </label>
                                    <div class="col-md-9">
                                        <div class="input-icon"><i class="fa fa-user"></i>
                                            <input id="inputIncludeFile" name="datafile" type="file"
                                                   placeholder="Inlcude some file">
                                        </div>
                                    </div>
                                </div>


                            </div>
                            <div class="form-actions">
                                <div class="col-md-offset-3 col-md-9">
                                    <button type="button" class="btn btn-primary" @click="commitData">上传</button>&nbsp;
                                    <button type="button" class="btn btn-green" @click="goback">返回</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div id="modal-alert-error" tabindex="-1" role="dialog" aria-hidden="true" class="modal fade">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" data-dismiss="modal" aria-hidden="true"
                            class="close">&times;
                    </button>
                    <h4 id="modal-default-label" class="modal-title">温馨提示</h4>
                </div>
                <div class="modal-body" style="color: red;text-align: center"><h3>[[errormessage]]</h3>
                </div>
                <div class="modal-footer">
                    <button type="button" data-dismiss="modal" class="btn btn-primary">Ok</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}


{% block page-scripts %}
    <script>
        var vm = new Vue({
            el: '#app',
            // 分割符: 修改vue中显示数据的语法, 防止与django冲突
            delimiters: ['[[', ']]'],
            components: {},
            data: {
                Title: "",
                Abstract: "",
                Content: "",
                RecType: "",
                imgList: [],
                dataTypeList: [],
                errormessage: "",
                size: 0
            },
            created() {
                this.getRsourceTypeData();
            },
            methods: {
                async getData() {
                    //获取交流主记录
                    let data = {id: ""};
                    let res = await axiosget("{% url 'get_datatype' %}", data);
                    console.log(res);
                    if (res.code == 200) {
                        this.dataTypeList = res.data.items;
                    }
                },
                async getRsourceTypeData() {
                    //获取数据类型字典
                    let data = {id: ""};
                    let res = await axiosget("{% url 'get_datatype' %}", data);
                    console.log(res);
                    if (res.code == 200) {
                        this.dataTypeList = res.data.items;
                    }
                },
                async commitData() {
                    //校对数据
                    if (this.RecType == "") {
                        this.errormessage = "数据类型未选择！";
                        $('#modal-alert-error').modal('show');
                        return;
                    }
                    if (this.Title == "") {
                        this.errormessage = "标题未填写！";
                        $('#modal-alert-error').modal('show');
                        return;
                    }
                    if (this.Abstract == "") {
                        this.errormessage = "简介未填写！";
                        $('#modal-alert-error').modal('show');
                        return;
                    }
                    if (this.Content == "") {
                        this.errormessage = "详细描述未填写！";
                        $('#modal-alert-error').modal('show');
                        return;
                    }

                    var data = new FormData($('#uploadData')[0]);
                    //追加图片
                    for (let i = 0; i < this.imgList.length; i++) {

                        data.append('imagefile', this.imgList[i].file);
                    }
                    var xhr = new XMLHttpRequest();
                    xhr.upload.addEventListener('progress', this.on_progress, false);     //xhr对象含有一个upload对象，它有一个progress事件，在文件上传过程中会被不断触发，我们为这个事件对应一个处理函数，每当事件触发就会调用这个函数，于是便可利用这个函数来修改当前进度，更多细节可自行查询
                    xhr.open('POST', "{% url 'upload_data' %}", true);  //请将url改成上传url
                    xhr.setRequestHeader('X-CSRFTOKEN', '[[ request.COOKIES.csrftoken ]]');   //此处为Django要求，可无视，或者换成相应后台所要求的CSRF防护，不是django用户请去掉
                    xhr.send(data);   //发送表单
                    xhr.onreadystatechange = () => {
                        if (xhr.readyState == 4 || xhr.readyState == "complete") {
                            var resData = JSON.parse(xhr.responseText);
                            if (resData.code == 200) {
                                //跳转我的数据界面
                                  window.location.href = "{% url 'my_data' %}" ;

                            } else {
                                this.errormessage = resData.message;
                                $('#modal-alert-error').modal('show');
                            }
                        }
                    }
                },
                on_progress(evt) {       //看这个函数之前先看upload函数。这个函数可以接收一个evt(event)对象(细节自行查询progress)，他有3个属性lengthComputable，loaded，total，第一个属性是个bool类型的，代表是否支持，第二个代表当前上传的大小，第三个为总的大小，由此便可以计算出实时上传的百分比
                    if (evt.lengthComputable) {
                        var percent = Math.round((evt.loaded) * 100 / evt.total);
                        console.log(percent);
                        if (percent == 100) {
                            percent = 99;
                        }
                    }
                },
                goback() {
                    window.history.back(-1);
                },
                fileClick() {
                    document.getElementById('upload_file').click()
                },
                fileChange(el) {
                    if (!el.target.files[0].size) return;
                    this.fileList(el.target);
                    el.target.value = ''
                },
                fileList(fileList) {
                    let files = fileList.files;
                    for (let i = 0; i < files.length; i++) {
                        //判断是否为文件夹
                        if (files[i].type != '') {
                            this.fileAdd(files[i]);
                        } else {
                            //文件夹处理
                            this.folders(fileList.items[i]);
                        }
                    }
                },
                //文件夹处理
                folders(files) {
                    let _this = this;
                    //判断是否为原生file
                    if (files.kind) {
                        files = files.webkitGetAsEntry();
                    }
                    files.createReader().readEntries(function (file) {
                        for (let i = 0; i < file.length; i++) {
                            if (file[i].isFile) {
                                _this.foldersAdd(file[i]);
                            } else {
                                _this.folders(file[i]);
                            }
                        }
                    })
                },
                foldersAdd(entry) {
                    let _this = this;
                    entry.file(function (file) {
                        _this.fileAdd(file)
                    })
                },
                fileAdd(file) {
                    //总大小
                    this.size = this.size + file.size;
                    //判断是否为图片文件
                    if (file.type.indexOf('image') == -1) {
                        file.src = 'wenjian.png';
                        this.imgList.push({
                            file
                        });
                    } else {
                        let reader = new FileReader();
                        reader.vue = this;
                        reader.readAsDataURL(file);
                        reader.onload = function () {
                            file.src = this.result;
                            this.vue.imgList.push({
                                file
                            });
                        }
                    }
                },
                fileDel(index) {
                    this.size = this.size - this.imgList[index].file.size;//总大小
                    this.imgList.splice(index, 1);
                },
                bytesToSize(bytes) {
                    if (bytes === 0) return '0 B';
                    let k = 1000, // or 1024
                        sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
                        i = Math.floor(Math.log(bytes) / Math.log(k));
                    return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
                },
                dragenter(el) {
                    el.stopPropagation();
                    el.preventDefault();
                },
                dragover(el) {
                    el.stopPropagation();
                    el.preventDefault();
                },
                drop(el) {
                },
            },
            computed: {
                // 计算属性的 getter
            }
        });

        function sfzzmSc() {//点击触发h5File类型上
            $("#sfzzm").click();
        }

        function showpic(obj, id) {//图片展示
            //var imgs = document.getElementById("sfzzmImg").getElementsByTagName("img");
            for (var i = 0, file; file = obj.files[i]; i++) {
                if (i > 0) {
                    break;
                }
                const size200k = file.size / 1024 < 500;
                if (!size200k) {
                    console.log("图片超过500k");
                    $('#modal-alert99').modal('show');
                    $("#" + id).val("");
                    return false;
                }
                var reader = new FileReader();
                reader.onload = function (e) {//图片读取展示
                    console.log(e);
                    var htmlimg = '<img  style="margin-left:2px;width:300px; " id="' + e.timeStamp + '" class="min"  src="' + e.target.result + '" onclick="showBigPic(this)"/>';
                    $("#" + id + "Img").html(htmlimg);
                };
                reader.readAsDataURL(file);

            }
        }
    </script>

{% endblock %}

{% block page-styles %}
    <style>
        form {
            font-size: 12pt;
        }

        .upload_warp_img_div_del {
            position: absolute;
            top: 6px;
            width: 16px;
            right: 4px;
        }

        .upload_warp_img_div_top {
            position: absolute;
            top: 0;
            width: 100%;
            height: 30px;
            background-color: rgba(0, 0, 0, 0.4);
            line-height: 30px;
            text-align: left;
            color: #fff;
            font-size: 12px;
            text-indent: 4px;
        }

        .upload_warp_img_div_text {
            white-space: nowrap;
            width: 80%;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .upload_warp_img_div img {
            max-width: 100%;
            max-height: 100%;
            vertical-align: middle;
        }

        .upload_warp_img_div {
            position: relative;
            height: 100px;
            width: 120px;
            border: 1px solid #ccc;
            margin: 0px 30px 10px 0px;
            float: left;
            line-height: 100px;
            display: table-cell;
            text-align: center;
            background-color: #eee;
            cursor: pointer;
        }

        .upload_warp_img {
            border-top: 1px solid #D2D2D2;
            padding: 0px 0 0 0px;
            overflow: hidden
        }

        .upload_warp_text {
            text-align: left;
            margin-bottom: 10px;
            padding-top: 10px;
            text-indent: 14px;
            border-top: 1px solid #ccc;
            font-size: 14px;
        }

        .upload_warp_right {
            float: left;
            width: 57%;
            margin-left: 2%;
            height: 100%;
            border: 1px dashed #999;
            border-radius: 4px;
            line-height: 130px;
            color: #999;
        }

        .upload_warp_left img {
            margin-top: 0px;
        }

        .upload_warp_left {
            float: left;
            width: 70px;
            height: 70px;
        {#border: 1px dashed #999;#} border-radius: 4px;
            cursor: pointer;
        }

        .upload_warp {
            margin: 5px;
            height: 80px;
        }

        .upload {
            border: 1px solid #ccc;
            background-color: #fff;
            width: 650px;
            box-shadow: 0px 1px 0px #ccc;
            border-radius: 4px;
        }

    </style>

{% endblock %}